module.exports = function (plop) {
  // 导入所需模块
  const { exec } = require('child_process');
  const path = require('path');
  const fs = require('fs');

  // 定义打开文件的函数
  function openFile(filePath) {
    const fullPath = path.resolve(process.cwd(), filePath);
    if (fs.existsSync(fullPath)) {
      console.log(`\n正在打开文件: ${fullPath}`);
      
      // 根据操作系统选择打开方式
      const isWin = process.platform === 'win32';
      
      // Windows - 尝试使用cursor打开
      exec(`cursor "${fullPath}"`, (error) => {
        if (error) {
          // 如果VS Code不可用，尝试使用默认程序打开
          console.log(`打开文件失败: ${error},文件路径: ${fullPath}`);
        }
      });
    }
    return '文件已创建';
  }

  // 添加页面到pages.json
  function addPageToConfig(answers) {
    try {
      const pagesConfigPath = path.resolve(process.cwd(), 'pages.json');
      
      if (!fs.existsSync(pagesConfigPath)) {
        return '无法找到pages.json';
      }
      
      // 读取pages.json文件内容
      let fileContent = fs.readFileSync(pagesConfigPath, 'utf8');
      
      // 查找pages数组的结束括号位置
      const lastBracketIndex = fileContent.lastIndexOf(']');
      if (lastBracketIndex === -1) {
        return '无法在pages.json中找到pages数组';
      }
      
      // 检查pages数组是否为空
      const pagesArrayContent = fileContent.substring(
        fileContent.indexOf('"pages"'), 
        lastBracketIndex
      );
      
      // 是否需要添加逗号（如果数组中已有内容）
      const needComma = pagesArrayContent.includes('{');
      
      // 新页面的配置信息
      const newPageConfig = `${needComma ? ',' : ''}
		{
			"path": "pages/${plop.getHelper('pascalCase')(answers.name)}/${plop.getHelper('pascalCase')(answers.name)}",
			"style": {
				"navigationBarTitleText": "${answers.title}"
			}
		}`;
      
      // 将新页面添加到数组末尾
      fileContent = fileContent.substring(0, lastBracketIndex) + 
                    newPageConfig + 
                    fileContent.substring(lastBracketIndex);
      
      // 保存更新后的文件
      fs.writeFileSync(pagesConfigPath, fileContent, 'utf8');
      
      return 'pages.json已更新';
    } catch (error) {
      console.error('更新pages.json时出错:', error);
      return `更新配置失败: ${error.message}`;
    }
  }

  // 新建组件
  plop.setGenerator("component", {
    description: "新建组件",
    prompts: [
      {
        type: "input",
        name: "name",
        message: "要新建的组件名:",
      },
    ],
    actions: [
      {
        type: "add",
        path: "components/{{pascalCase name}}/{{pascalCase name}}.vue",
        templateFile: "plop-templates/Component.vue.hbs",
      },
      function(answers) {
        const filePath = `components/${plop.getHelper('pascalCase')(answers.name)}/${plop.getHelper('pascalCase')(answers.name)}.vue`;
        return openFile(filePath);
      }
    ],
  });

  // 新建页面
  plop.setGenerator("page", {
    description: "新建页面",
    prompts: [
      {
        type: "input",
        name: "name",
        message: "要新建的页面名:",
      },
      {
        type: "input",
        name: "title",
        message: "要新建的页面标题:",
      },
    ],
    actions: [
      {
        type: "add",
        path: "pages/{{pascalCase name}}/{{pascalCase name}}.vue",
        templateFile: "plop-templates/page.vue.hbs",
      },
      addPageToConfig,
      function(answers) {
        const filePath = `pages/${plop.getHelper('pascalCase')(answers.name)}/${plop.getHelper('pascalCase')(answers.name)}.vue`;
        return openFile(filePath);
      }
    ],
  });

  // 新建接口文件
  plop.setGenerator("api", {
    description: "新建接口文件",
    prompts: [
      {
        type: "input",
        name: "name",
        message: "要新建的接口文件名:",
      },
    ],
    actions: [
      {
        type: "add",
        path: "api/{{pascalCase name}}.js",
        templateFile: "plop-templates/api.js.hbs",
      },
      function(answers) {
        const filePath = `api/${plop.getHelper('pascalCase')(answers.name)}.js`;
        return openFile(filePath);
      }
    ],
  });
};
